package cassandrawindow;

import com.vcc.BO.NewsPageView;
import com.vcc.dao.cassandra.PageViewDAOImpl;
import com.vcc.util.config.ConfigUtil;
import com.vcc.util.config.SystemInfo;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 *
 * @author quyennb
 */
public class HandleCoverPage {

    public static final int NUMBER_NEWS_COVER_PAGE          = 100;
    public static final int CAT_XAHOI                       = 1;
    public static final int CAT_THEGIOI                     = 3;
    public static final int CAT_PHAPLUAT                    = 2;
    public static final int CAT_GIAITRI                     = 10;
    public static final int CAT_CONGNGHE                    = 7;
    public static final int CAT_THETHAO                     = 9;

    public static final int MINUTE_INTEVAL                 = 5;

    public static final int COFF_DUPLICATE                 = 1;
    public static final int COFF_RANKBYTIME                = 1;
    
    //sort value of result
    static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
            SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
                new Comparator<Map.Entry<K,V>>() {
                    @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
                        int res = e1.getValue().compareTo(e2.getValue());
                        return res != 0 ? res : 1; // Special fix to preserve items with equal values
                    }
                }
            );
            sortedEntries.addAll(map.entrySet());
            return sortedEntries;
        }

        public void handleData() throws IOException{
            /*lay nhung tin xuat hien tren nhieu bao nhat
             * sau Ä‘Ã³ nhá»¯ng tin cÃ²n láº¡i thÃ¬ láº¥y hÃªt á»Ÿ bÃ¡o dan tri,nhÆ°ng khong duoc trung nhau
             * nhung tin nÃ o trÃ¹ng nhau nháº¥t cho rank = 1
             * náº¿u trung nhau Ã­t hÆ¡n thi cho rank random
             */
                         
            //1.láº¥y nhÆ°ng tin trung nhau nháº¥t (la tin hot nhÃ¢t)                               
            MysqlDataManager mysql = new MysqlDataManager();

            //get currentDate
            String currentDate = TimeUtil.getCurrentTimeInString();//2012-07-24
            Map<Long, Long> allHotNewBySourceId = new HashMap<>();

            Map<Long, Long> hotNews = new HashMap<>();
            /*
             * get all hot news
             */
            getAllHotNews(allHotNewBySourceId,hotNews,currentDate);
            /*
             * get simility
             *
             */
            List listSimi = new ArrayList();            
            listSimi = omitSimility(allHotNewBySourceId, hotNews);
            /*
             *3.lay nhung hot_id cua nhung tin trung nhau
             */
            List infor = new ArrayList();
            Set s = hotNews.entrySet();            
            Iterator it=s.iterator();

            while(it.hasNext())
            {
                Map.Entry m =(Map.Entry)it.next();
                //key la userid
                long key=(Long)m.getKey();
                mysql.getHotNewByCrawlerId(infor,key);
            }
            
            //4. map nhung id cua 2 map countHotNewCoverPage,hotNews va danh lai rank
            //dong thoi check newid bi trung giua hai map countHotNewCoverPage,hotNews
            Set s1 = allHotNewBySourceId.entrySet();
            Iterator it1=s1.iterator();
            int countHotNewCoverPage = hotNews.size();
            SqlServerDataManager sqlserver = new SqlServerDataManager();                 
                       
            while(it1.hasNext())
            {
                Map.Entry m =(Map.Entry)it1.next();
                //key la news_id
                long key=(Long)m.getKey();
                //neu khong trung voi nhung id da lay thi add vao map moi
                if(!infor.contains(key))
                {
                    countHotNewCoverPage ++;
                    hotNews.put((Long) m.getValue(), 1L);
                    if(countHotNewCoverPage == NUMBER_NEWS_COVER_PAGE) break;
                }
            }
            /*get score của các NewsID
             * Rank = d +n +a
             */
            Map<Long, Double> rankChangeByTime = new HashMap<>();
            Map<Long, Double> rankChangeByTime_xahoi = new HashMap<>();
            rankChangeByTime_xahoi = mysql.getRankChangeByTime(CAT_XAHOI,50);
            rankChangeByTime.putAll(rankChangeByTime_xahoi);
            Map<Long, Double> rankChangeByTime_thegioi = new HashMap<>();
            rankChangeByTime_thegioi = mysql.getRankChangeByTime(CAT_THEGIOI,1);
            rankChangeByTime.putAll(rankChangeByTime_thegioi);
            Map<Long, Double> rankChangeByTime_kinhte = new HashMap<>();
            rankChangeByTime_kinhte = mysql.getRankChangeByTime(CAT_CONGNGHE,2);
            rankChangeByTime.putAll(rankChangeByTime_kinhte);
            Map<Long, Double> rankChangeByTime_giaitri = new HashMap<>();
            rankChangeByTime_giaitri = mysql.getRankChangeByTime(CAT_GIAITRI,14);
            rankChangeByTime.putAll(rankChangeByTime_kinhte);
            Map<Long, Double> rankChangeByTime_thethao = new HashMap<>();
            rankChangeByTime_thethao = mysql.getRankChangeByTime(CAT_THETHAO,1);
            rankChangeByTime.putAll(rankChangeByTime_thethao);
            
            Set keys = hotNews.keySet();
            for (Iterator i = keys.iterator(); i.hasNext();) {                  
                  Long key = (Long) i.next();                 
                  rankChangeByTime.put(key, 1D);
            }            

            //5.gan 2 map vao : valRets & hotNews va lay gia tri
            //map moi nay se co key la id va value tu 1-> n,n la so lan lap nhieu nhat
            //del hot new cu va insert hot new moi
            int rank = NUMBER_NEWS_COVER_PAGE;
            for (Entry<Long,Double> entry  : entriesSortedByValues(rankChangeByTime)) {
                System.out.println(entry.getKey()+","+entry.getValue());
                long NewsID = entry.getKey();
                //neu newsid khong trung thi ok
                if(!listSimi.contains(NewsID))
                {
                    //if exist
                    if(sqlserver.checkExistByNewsId(NewsID))
                    {
                        //if not is selected
                        if(!sqlserver.checkIsSelectedByNewsId(NewsID))
                        {
                            //update in db
                            sqlserver.updateRankByNewsId(NewsID, rank);
                            //Debug.println("update successfully");
                        }
                        //if is selected -> nothing
                    }
                    //if not exist-> insert
                    else {                       
                        String strSQL = mysql.getAllValueHotNewCoverPageByNewsIdV3(NewsID, rank,currentDate);
                        //insert in db
                        sqlserver.insertHotNewCoverPage(strSQL);
                        //Debug.println("insert successfully");
                    }
                    rank --;
                }
            }                                  
            Debug.println("cover page successfully");
        }
        
        public List omitSimility(Map map1,Map map2)
        {          
             /*
             *Check simility in HotNews
             */
            List infor1 = new ArrayList();
            //get all simility
            MysqlDataManager mysql = new MysqlDataManager();           
            Map<Long, Long> mapSimility = new HashMap<>();
            mapSimility.putAll(map1);
            mapSimility.putAll(map2);                                    
            //find simility
            Set s_simi = mapSimility.entrySet();
            Iterator it_simi=s_simi.iterator();
            int simi = 0 ;
            while(it_simi.hasNext())
            {
                Map.Entry m =(Map.Entry)it_simi.next();
                //key la userid
                long key=(Long)m.getKey();
                //infor1 = mysql.getAllsimility();
                mysql.getAllsimilityByNewsID(key,infor1);
                simi ++;
            }
            
            System.out.println("simility:"+simi);
            return infor1;
        }

        public void getAllHotNews(Map allHotNewBySourceId,Map hotNews,String currentDate)
        {
            MysqlDataManager mysql = new MysqlDataManager();
            List hotNewsByCat = new ArrayList();
            /*lay nhung tin xuat hien tren nhieu bao nhat
             * sau Ä‘Ã³ nhá»¯ng tin cÃ²n láº¡i thÃ¬ láº¥y hÃªt á»Ÿ bÃ¡o dan tri,nhÆ°ng khong duoc trung nhau
             * nhung tin nÃ o trÃ¹ng nhau nháº¥t cho rank = 1
             * náº¿u trung nhau Ã­t hÆ¡n thi cho rank random
             */
            //1.láº¥y nhÆ°ng tin trung nhau nháº¥t (la tin hot nhÃ¢t)
            //get currentDate           
            mysql.getDuplicateHotNews(currentDate,hotNews);
            System.out.println("hot new:"+hotNews);
            //2.lay nhung tin con lai tren bao dan tri ,id =1
          /*for(int i = 1 ; i <= 7; i++)
            {
                //down vietnamnet
                //if(i == 4) continue;
                Map<Long, Long> map1 = new HashMap<>();
                map1 = mysql.getAllHotNewBySourceId(i,currentDate);
                allHotNewBySourceId.putAll(map1);
                //neu lay tong so tin hot va tin hot tren 1 bao khong bang NUMBER_NEWS_COVER_PAGE thi phai tim bao khac
                if(allHotNewBySourceId.size() + hotNews.size() >= NUMBER_NEWS_COVER_PAGE)
                {
                    break;
                }
            }
            //nếu tống số tin vẫn  < NUMBER_NEWS_COVER_PAGE thi lay theo ti le 7:2:1 trong new recommend
            if(allHotNewBySourceId.size() + hotNews.size() <= NUMBER_NEWS_COVER_PAGE)
            {
                hotNewsByCat = getNewsIDByAllCat();
                //insert in Hot New
                Iterator itr = hotNewsByCat.iterator();
                while(itr.hasNext()) {
                    Long element = (Long) itr.next();
                    allHotNewBySourceId.put(element, 1L);
                }
            }      */

        }

        public List getNewsIDByAllCat()
        {
            List infor = new ArrayList();
            //get ALL news by cat_id
            MysqlDataManager mysql = new MysqlDataManager();
            mysql.getNewsIDbyCat(CAT_XAHOI, 5, infor);
            mysql.getNewsIDbyCat(CAT_PHAPLUAT, 1, infor);
            mysql.getNewsIDbyCat(CAT_CONGNGHE, 3, infor);
            mysql.getNewsIDbyCat(CAT_GIAITRI, 3, infor);
            mysql.getNewsIDbyCat(CAT_THETHAO, 2, infor);
            mysql.getNewsIDbyCat(CAT_THEGIOI, 1, infor);
            return infor;
        }

       

}
